﻿@using Abp.Application.Navigation;
@using Abp.Notifications;
@inherits LayoutComponentBase
@inject IUnitOfWorkManager uowManager
@inject IUserNavigationManager abpNavManager
@inject NavigationManager blazorNavManager
@inject Abp.Events.Bus.IEventBus eventBus
@inject ISnackbar snackbar
@inject IAbpSession abpSession
@inject TrackingCircuitHandler circuitHandler
@inject BXJG.Common.Zhongjie zhongjie
@implements IDisposable

<PageTitle>小管印</PageTitle>

<MudThemeProvider Theme="MyCustomTheme" />
<MudDialogProvider />
<MudSnackbarProvider />

<MudLayout>
    <MudAppBar>
        <MudIconButton Icon="@Icons.Material.Filled.Menu" Edge="Edge.Start" OnClick="@((e) => DrawerToggle())" />
        <MudBreadcrumbs Items="_items"></MudBreadcrumbs>
        <MudSpacer />
        <MudStack Row="true" AlignItems="AlignItems.Center">
            @*关联的部门/角色等辅助显示*@
            @* <MudHidden Breakpoint="@Breakpoint.Xs">
            <MudText Style="padding-top:.7rem; "  Typo="Typo.body2">管理员</MudText>
            </MudHidden>*@
            <MudText Typo="Typo.body2">
                总在线用户：@circuitHandler.ConnectedCircuits
            </MudText>


            <MudMenu FullWidth="false" Dense ActivationEvent="MouseEvent.MouseOver" AnchorOrigin="Origin.BottomCenter" TransformOrigin="Origin.TopCenter">
                 <ActivatorContent>
                     <MudChip Icon="@Icons.Material.Filled.Person">管理员</MudChip>
                 </ActivatorContent>
                 <ChildContent>
                     <MudMenuItem>我的资料</MudMenuItem>
                     <MudMenuItem><a href="/account/logout?appKey=admin">退出系统</a></MudMenuItem>
                 </ChildContent>
             </MudMenu>
         </MudStack>
     </MudAppBar>

     <MudDrawer @bind-Open="@_drawerOpen" Width="12rem;" Variant="@DrawerVariant.Mini" OpenMiniOnHover="true">
         <MudDrawerHeader Class="mud-theme-primary" Style="padding:12px 0 0 12px; width:12rem;">
             @if (_drawerOpen)
            {
                <MudStack Row Spacing="2">
                     <MudIcon Icon="@Icons.Custom.Brands.Discord" Color="Color.Surface" Size="Size.Large" />
                     <MudText Align="Align.Center" Typo="Typo.h6" Style="line-height:2.2rem;">
                         @if (_drawerOpen)
                        {
                            @:小管印
                        }
                    </MudText>
                </MudStack>
            }
            else
            {
                <MudIcon Icon="@Icons.Custom.Brands.Discord" Color="Color.Surface" Size="Size.Large" />
            }
        </MudDrawerHeader>
        @*<MudDrawerContainer>
        士大夫地方
        </MudDrawerContainer>*@
        <MudNavMenu Margin="Margin.Normal" Color="Color.Surface" Bordered="true" Dense="false">
            @* <MudNavLink Href="/admin" Match="NavLinkMatch.All" Icon="@Icons.Material.Outlined.Home">控制台</MudNavLink> *@
            @if (menu != null)
            {
                foreach (var item in menu.Items)
                {
                    @if (item.Items != default && item.Items.Any())
                    {
                        <MudNavGroup Title="@(_drawerOpen?item.DisplayName:string.Empty)" Style="width:12rem;" Icon="@item.Icon" HideExpandIcon="@(!_drawerOpen)">

                            @foreach (var item2 in item.Items)
                            {
                                <MudNavLink Href="@item2.Url" Match="NavLinkMatch.All" Icon="@item2.Icon" Style="width:12rem;">
                                    @if (_drawerOpen)
                                    {
                                        @item2.DisplayName
                                    }
                                </MudNavLink>
                            }
                        </MudNavGroup>
                    }
                    else
                    {
                        <MudNavLink Href="@item.Url" Match="NavLinkMatch.All" Icon="@item.Icon" Style="width:12rem;">
                            @if (_drawerOpen)
                            {
                                @item.DisplayName
                            }
                        </MudNavLink>
                    }
                }
            }
        </MudNavMenu>
    </MudDrawer>

    <MudMainContent Style="height:100%;">
        <ErrorBoundary>
            <ChildContent>
                <MudContainer MaxWidth="@MaxWidth.False" Style="padding:1rem;  position:relative; height:100%;">
                    @Body
                </MudContainer>
            </ChildContent>
            <ErrorContent>
                <p class="errorUI">服务端发生未处理异常！请稍后刷新重试。 @context.StackTrace</p>
                <environment include="Development">
                    <p class="errorUI"> @context.Message</p>
                    <p class="errorUI">@(new MarkupString(context.InnerException?.StackTrace))</p>
                </environment>
            </ErrorContent>
        </ErrorBoundary>
    </MudMainContent>
</MudLayout>
@code {
    MudTheme MyCustomTheme = new MudTheme()
        {
            Palette = new Palette()
            {
                Primary = Colors.Blue.Darken3,
                Background = Colors.Grey.Lighten4,
                //Secondary = Colors.Green.Accent4,
                AppbarBackground = Colors.Shades.White,
                AppbarText = Colors.Green.Darken4,
                DrawerBackground = Colors.Blue.Darken4,
                DrawerIcon = Colors.Blue.Lighten5,
                DrawerText = Colors.Blue.Lighten5
            },
            //PaletteDark = new PaletteDark()
            //{
            //    Primary = Colors.Blue.Lighten1
            //},
            //LayoutProperties = new LayoutProperties()
            //{
            //    DrawerWidthLeft = "260px",
            //    DrawerWidthRight = "300px"
            //}
        };

    bool _drawerOpen = true;
    //GetCurrentLoginInformationsOutput appSession;//=new GetCurrentLoginInformationsOutput();
    void DrawerToggle()
    {
        _drawerOpen = !_drawerOpen;
    }
    UserMenu menu;
    //路径
    private List<BreadcrumbItem> _items = new List<BreadcrumbItem>();
    ////顶部的注入不晓得为啥不行，但非布局页又可以
    //IAbpSession abpSession => AbpSession.Value;
    //通知事件注销对象
    IDisposable tzsj = default;

    protected override void OnInitialized()
    {
        currUserId = abpSession.UserId;
        tzsj?.Dispose();
        tzsj = zhongjie.Zhuce<BXJG.Utils.Notification.NotificationEventData>(EventNotify);
        dianhubianhua?.Dispose();
        dianhubianhua = zhongjie.Zhuce(async () => await InvokeAsync(StateHasChanged), "TrackingCircuitChanged");
        blazorNavManager.LocationChanged += HandleLocationChanged;
    }
    IDisposable dianhubianhua;
    //[UnitOfWork(false)] 手动刷新执行两次，用这个好像也会出问题，还是代码内部手动开启吧
    //https://learn.microsoft.com/zh-cn/aspnet/core/blazor/components/lifecycle?view=aspnetcore-7.0#stateful-reconnection-after-prerendering
    protected override async Task OnInitializedAsync()
    {
       

        //f5刷新时，此时可能出现工作单元释放，最终导致事务不生效，所以init中必须手动开启事务
        using var scope = uowManager.Begin(new UnitOfWorkOptions { IsTransactional = false });
        // appSession = (await sessionService.GetCurrentLoginInformations()) as GetCurrentLoginInformationsOutput;
        //if (appSession.User != default)
        //{
        //    menu = await abpNavManager.GetMenuAsync(PermissionNames.Customer, new Abp.UserIdentifier(appSession.Tenant.Id, appSession.User.Id));
        //}


        if (abpSession.UserId.HasValue)
            menu = await abpNavManager.GetMenuAsync("adminBlazor", new Abp.UserIdentifier(abpSession.TenantId, abpSession.UserId.Value));
    }
    long? currUserId;
    private async ValueTask EventNotify(BXJG.Utils.Notification.NotificationEventData d)
    {
        foreach (var item in d.UserNotifications)
        {
            if (item.UserId != currUserId)
                continue;

            Severity severity = Severity.Normal;
            switch (item.Notification.Severity)
            {
                case NotificationSeverity.Info:
                    severity = Severity.Normal;
                    break;
                case NotificationSeverity.Success:
                    severity = Severity.Success;
                    break;
                case NotificationSeverity.Warn:
                    severity = Severity.Warning;
                    break;
                case NotificationSeverity.Error:
                    severity = Severity.Error;
                    break;
                case NotificationSeverity.Fatal:
                    severity = Severity.Error;
                    break;
                default:
                    break;
            }
            var msg = string.Empty;
            if (item.Notification.Data is Abp.Notifications.MessageNotificationData v)
                msg = v.Message;
            else
                msg = item.Notification.Data.ToString();

            snackbar.Add(msg, severity, opt =>
            {
                opt.VisibleStateDuration = 10000;
            });
        }
    }

    private void HandleLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        // if (menu == default)
        //     return;
        // var curr = this.menu.Items.SingleOrDefault(c => e.Location.EndsWith(c.Url, StringComparison.OrdinalIgnoreCase));
        // if (curr == default)
        //     return;
        // this._items = new List<BreadcrumbItem> { new BreadcrumbItem(curr.DisplayName, curr.Url) };
        // StateHasChanged();
    }
    public void Dispose()
    {
        dianhubianhua?.Dispose();
        tzsj?.Dispose();
        blazorNavManager.LocationChanged -= HandleLocationChanged;
    }
}